package com.bawei.module_mine.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.aop.LoginManager
import com.bawei.lib_common.utils.UserUtils
import com.bawei.module_mine.R
import com.bawei.module_mine.databinding.ActivityProfileBinding
import com.bawei.module_mine.utils.AvatarUtils
import com.bumptech.glide.Glide
import com.google.android.material.bottomsheet.BottomSheetDialog
import java.io.IOException

@Route(path = "/module_mine/ProfileActivity")
class ProfileActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityProfileBinding
    private lateinit var pickImageLauncher: ActivityResultLauncher<Intent>
    private lateinit var cameraLauncher: ActivityResultLauncher<Intent>
    private lateinit var requestPermissionLauncher: ActivityResultLauncher<Array<String>>
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityProfileBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        initView()
        initData()
        initAvatarPick()
        binding.ivAvatar.setOnClickListener {
            showAvatarPickDialog()
        }
    }
    
    private fun initView() {
        // 设置返回按钮
        binding.ivBack.setOnClickListener {
            finish()
        }
        
        // 设置设置按钮
        binding.ivSettings.setOnClickListener {
            showMsg("跳转到设置页面")
        }
        
        // 设置编辑资料按钮
        binding.tvEditProfile.setOnClickListener {
            showMsg("跳转到编辑资料页面")
        }
        
        // 设置用户名点击事件 - 跳转到一键登录
        binding.tvUsername.setOnClickListener {
            try {
                // 使用LoginManager管理跳转，防止重复页面
                val jumped = LoginManager.navigateToQuickLogin(this)
                if (!jumped) {
                    Log.d("ProfileActivity", "跳转被阻止，可能登录页面已显示或跳转过于频繁")
                }
            } catch (e: Exception) {
                Log.e("ProfileActivity", "跳转到一键登录失败: ${e.message}", e)
                showMsg("跳转失败")
            }
        }
        
        // 设置统计数据点击事件
        binding.layoutFollowing.setOnClickListener {
            showMsg("查看关注列表")
        }
        
        binding.layoutFollowers.setOnClickListener {
            showMsg("查看粉丝列表")
        }
        
        binding.layoutLikes.setOnClickListener {
            showMsg("查看获赞列表")
        }
        
        // 设置功能列表点击事件
        binding.layoutMyWorks.setOnClickListener {
            showMsg("跳转到我的作品页面")
        }
        
        binding.layoutMyFavorites.setOnClickListener {
            try {
                ARouter.getInstance().build("/module_mine/StoreActivity").navigation()
            } catch (e: Exception) {
                Log.e("ProfileActivity", "跳转到收藏页面失败: ${e.message}", e)
                showMsg("跳转失败")
            }
        }
        
        binding.layoutWatchHistory.setOnClickListener {
            showMsg("跳转到观看历史页面")
        }
        
        binding.layoutOfflineCache.setOnClickListener {
            showMsg("跳转到离线缓存页面")
        }
        
        // 设置设置列表点击事件
        binding.layoutAccountSettings.setOnClickListener {
            showMsg("跳转到账号设置页面")
        }
        
        binding.layoutPrivacySettings.setOnClickListener {
            showMsg("跳转到隐私设置页面")
        }
        
        binding.layoutHelpFeedback.setOnClickListener {
            showMsg("跳转到帮助与反馈页面")
        }
        
        binding.layoutAboutUs.setOnClickListener {
            showMsg("跳转到关于我们页面")
        }
        
        // 根据登录状态设置按钮
        setupLoginButton()
    }
    
    /**
     * 根据登录状态设置按钮
     */
    private fun setupLoginButton() {
        val isLoggedIn = LoginManager.isLoggedIn()
        
        if (isLoggedIn) {
            // 已登录状态：显示退出登录按钮
            binding.btnLogout.text = "退出登录"
            binding.btnLogout.setBackgroundColor(getColor(android.R.color.holo_red_dark))
            binding.btnLogout.setOnClickListener {
                // 退出登录
                // 1. 使用LoginManager的logout方法，会设置冷却期标记
                LoginManager.logout()
                
                // 2. 清除本地用户信息
                UserUtils.clearLoginInfo()
                
                // 3. 显示退出成功提示
                showMsg("已退出登录")
                
                // 4. 关闭当前页面
                finish()
            }
        } else {
            // 未登录状态：显示登录按钮
            binding.btnLogout.text = "立即登录"
            binding.btnLogout.setBackgroundColor(getColor(R.color.colorPrimary))
            binding.btnLogout.setOnClickListener {
                try {
                    // 跳转到一键登录页面
                    val jumped = LoginManager.navigateToQuickLogin(this)
                    if (!jumped) {
                        Log.d("ProfileActivity", "跳转被阻止，可能登录页面已显示或跳转过于频繁")
                    }
                } catch (e: Exception) {
                    Log.e("ProfileActivity", "跳转到一键登录失败: ${e.message}", e)
                    showMsg("跳转失败")
                }
            }
        }
    }
    
    private fun initData() {
        loadUserInfo()
    }
    
    /**
     * 加载用户信息
     */
    private fun loadUserInfo() {
        try {
            // 获取当前用户ID
            val userId = UserUtils.getCurrentUserId()
            
            if (userId.isNotEmpty()) {
                // 用户已登录，显示用户信息
                binding.tvUsername.text = "用户${userId.takeLast(4)}" // 显示用户ID后4位
                binding.tvUserId.text = "ID: $userId"
                binding.tvBio.text = "这个人很懒，什么都没有留下..."
                
                // 设置统计数据（这里可以根据实际数据调整）
                binding.tvFollowingCount.text = "128"
                binding.tvFollowersCount.text = "1,234"
                binding.tvLikesCount.text = "5,678"
                
                Log.d("ProfileActivity", "加载用户信息成功，用户ID: $userId")
            } else {
                // 用户未登录，显示默认信息
                binding.tvUsername.text = "未登录用户"
                binding.tvUserId.text = "ID: 未登录"
                binding.tvBio.text = "请先登录查看个人信息"
                
                binding.tvFollowingCount.text = "0"
                binding.tvFollowersCount.text = "0"
                binding.tvLikesCount.text = "0"
                
                Log.d("ProfileActivity", "用户未登录，显示默认信息")
            }
        } catch (e: Exception) {
            Log.e("ProfileActivity", "加载用户信息失败: ${e.message}", e)
            showMsg("加载用户信息失败")
        }
    }
    
    /**
     * 显示消息提示
     */
    private fun showMsg(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
    
    override fun onResume() {
        super.onResume()
        // 每次页面恢复时刷新用户信息
        loadUserInfo()
        
        // 重新设置按钮状态
        setupLoginButton()
        
        // 每次页面恢复时刷新头像
        val userId = UserUtils.getCurrentUserId()
        val avatarPath = AvatarUtils.getAvatarPath(this, userId)
        if (avatarPath != null) {
            Glide.with(this).load(avatarPath).circleCrop().into(binding.ivAvatar)
        } else {
            Glide.with(this).load(R.drawable.logo).circleCrop().into(binding.ivAvatar)
        }
    }

    private fun initAvatarPick() {
        // 权限申请
        requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
            val granted = result[Manifest.permission.READ_EXTERNAL_STORAGE] == true && result[Manifest.permission.CAMERA] == true
            if (granted) {
                showAvatarPickDialog()
            } else {
                Toast.makeText(this, "请授予相机和存储权限", Toast.LENGTH_SHORT).show()
            }
        }
        // 相册选择
        pickImageLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val uri = result.data?.data
                uri?.let { handleImageUri(it) }
            }
        }
        // 自定义相机
        cameraLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val uri = result.data?.data
                uri?.let { handleImageUri(it) }
            }
        }
    }

    private fun showAvatarPickDialog() {
        val dialog = BottomSheetDialog(this)
        val view = LayoutInflater.from(this).inflate(R.layout.dialog_avatar_pick, null)
        view.findViewById<TextView>(R.id.tv_pick_album).setOnClickListener {
            dialog.dismiss()
            pickFromAlbum()
        }
        view.findViewById<TextView>(R.id.tv_pick_camera).setOnClickListener {
            dialog.dismiss()
            // 启动自定义相机Activity
            cameraLauncher.launch(Intent(this, CameraActivity::class.java))
        }
        view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener { dialog.dismiss() }
        dialog.setContentView(view)
        dialog.show()
    }

    private fun pickFromAlbum() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        pickImageLauncher.launch(intent)
    }

    private fun handleImageUri(uri: Uri) {
        try {
            val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                val source = ImageDecoder.createSource(contentResolver, uri)
                // Force software bitmap to prevent "Software rendering doesn't support hardware bitmaps"
                ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
                    decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
                }
            } else {
                MediaStore.Images.Media.getBitmap(contentResolver, uri)
            }
            // 保存为当前用户头像
            val userId = UserUtils.getCurrentUserId()
            AvatarUtils.saveAvatar(this, userId, bitmap)
            // 显示圆形头像
            Glide.with(this).load(bitmap).circleCrop().into(binding.ivAvatar)
        } catch (e: IOException) {
            e.printStackTrace()
            Toast.makeText(this, "头像设置失败", Toast.LENGTH_SHORT).show()
        }
    }
} 